namespace Microsoft.ServiceModel.Samples.Discovery
{
    using System;
    using System.Collections.Generic;
    using System.ServiceModel;
    using System.ServiceModel.Description;

    internal class DiscoveryServiceExtension : IExtension<ServiceHostBase>
    {
        static ServicePublisher sharedPublisher = new ServicePublisher();

        IEnumerable<ServiceProperties> serviceProperties;
        EventHandler openHandler;
        EventHandler closeHandler;
        
        internal DiscoveryServiceExtension(IEnumerable<ServiceProperties> serviceProperties)
        {
            this.serviceProperties = serviceProperties;
        }

        #region IExtension<ServiceHostBase> Members

        void IExtension<ServiceHostBase>.Attach(ServiceHostBase owner)
        {
            this.openHandler = new EventHandler(this.ServiceHostOpened);
            this.closeHandler = new EventHandler(this.ServiceHostClosed);

            owner.Opened += this.openHandler;
            owner.Closed += this.closeHandler;
        }

        void IExtension<ServiceHostBase>.Detach(ServiceHostBase owner)
        {
            if (this.openHandler != null)
                owner.Opened -= this.openHandler;

            if (this.closeHandler != null)
                owner.Closed -= this.closeHandler;
        }

        #endregion

        void ServiceHostOpened(object sender, EventArgs e)
        {
            foreach (ServiceProperties props in this.serviceProperties)
                sharedPublisher.Publish(props);
        }

        void ServiceHostClosed(object sender, EventArgs e)
        {
            foreach (ServiceProperties props in this.serviceProperties)
                sharedPublisher.Unpublish(props);
        }
    }
}